import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;

import org.imgscalr.Scalr;
import org.imgscalr.Scalr.Method;
import org.imgscalr.Scalr.Mode;


public class BackGroundPanel extends JPanel{
	
	private static final long serialVersionUID = -656231356L;
	private static ArrayList<BufferedImage> blood = new ArrayList<BufferedImage>();
	private static final File bloodDir = new File("Sangue");
	private BufferedImage back = null;
	private int resizeTime = 0;
    private int w = 640;
    private int h = 640;
    
    public BackGroundPanel(Dimension size) {
    	super(null);
    	this.w = size.width;
    	this.h = size.height;
    	this.setOpaque(true);
    	this.setBounds(0, 0, w, h);
    	new Timer().scheduleAtFixedRate(new Reload(), 100, 1000);
    	if(blood.size() == 0){
    		File[] img = bloodDir.listFiles();
    		for(File f : img)
				try {
					BufferedImage temp = ImageIO.read(f);
					blood.add(Scalr.resize(temp, 200));
				} catch (IOException e) {
					e.printStackTrace();
				}
    	}
	}
    
    public void addBlood(Point p){
    	Random r = new Random();
    	BufferedImage temp = blood.get(r.nextInt(blood.size()));
    	JLabel l = new JLabel(new ImageIcon(temp));
    	l.setBounds(p.x, p.y, l.getPreferredSize().width, l.getPreferredSize().height);
    	add(l);
    }
    
    @Override
    public void setPreferredSize(Dimension d) {
    	super.setPreferredSize(d);
    	this.w = d.width;
    	this.h = d.height;
    	this.setBounds(0, 0, w, h);
    	resizeTime = 0;
    }
    
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if(back == null){
        	try {
        		back = ImageIO.read(new File("sfondo.jpg"));
    		} catch (IOException e1) {
    			e1.printStackTrace();
    		}
        }
        back = Scalr.resize(back, Method.QUALITY, Mode.FIT_EXACT, w, h);
        g.drawImage(back, 0, 0, null);
    }
    
    class Reload extends TimerTask {
		public void run() {
			if(resizeTime == 0)
				resizeTime = 1;
			else if(resizeTime == 1){
				try {
	        		back = ImageIO.read(new File("sfondo.jpg"));
	    		} catch (IOException e1) {
	    			e1.printStackTrace();
	    		}
				resizeTime = 2;
				repaint();
			}
		}
	}
    
}
